﻿-- =============================================
-- Script Template
-- =============================================
USE [uvp]
GO
/****** 对象:  UserDefinedFunction [dbo].[fn_sub_FindBatteryGrpState]    脚本日期: 05/26/2012 18:24:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[fn_sub_FindBatteryGrpState]
(@Logtime datetime,
@Generation tinyint,
@EquipID nvarchar(30),
@BatteryGrp nvarchar(50)
)
RETURNS TABLE

as 
RETURN 
(
 select top 1 * from(
						SELECT top 1 LogID,Generation,EquipID,BatteryGroup,Vval,Ival,[Status],LogTime,logtime-@Logtime as Distance FROM dbo.S_BatgrpSubLog s
							WHERE s.Generation=@Generation and s.EquipID=@EquipID and s.BatteryGroup=@BatteryGrp  and s.LogTime>=@Logtime order by s.LogTime ASC
						union all 
						SELECT top 1 LogID,Generation,EquipID,BatteryGroup,Vval,Ival,[Status],LogTime, @Logtime-logtime as Distance FROM dbo.S_BatgrpSubLog s
							WHERE s.Generation=@Generation and s.EquipID=@EquipID and s.BatteryGroup=@BatteryGrp  and s.LogTime<=@Logtime order by s.LogTime DESC
					)t order by t.Distance ASC
)

